﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;

namespace DAL
{
    public class Gbook
    {
        public bool SendMessage(String authorName, String eMail, String date, String bodyText)
        {
            int count;

            using (SqlConnection con = new SqlConnection())
            {
                con.ConnectionString = ConfigurationManager.ConnectionStrings["FProj"].ConnectionString;

                String strSQL = "INSERT INTO Gbook (AuthorName, AuthorEmail, Date, Text) VALUES (@AuthorName, @AuthorEmail, @Date, @Text)";
                SqlCommand comm = new SqlCommand(strSQL, con);

                SqlParameter param = new SqlParameter();
                param.ParameterName = "@AuthorName";
                param.Value = authorName;
                param.SqlDbType = SqlDbType.Text;
                comm.Parameters.Add(param);

                param = new SqlParameter();
                param.ParameterName = "@AuthorEmail";
                param.Value = eMail;
                param.SqlDbType = SqlDbType.Text;
                comm.Parameters.Add(param);

                param = new SqlParameter();
                param.ParameterName = "@Date";
                param.Value = date;
                param.SqlDbType = SqlDbType.DateTime;
                comm.Parameters.Add(param);

                param = new SqlParameter();
                param.ParameterName = "@Text";
                param.Value = bodyText;
                param.SqlDbType = SqlDbType.Text;
                comm.Parameters.Add(param);

                con.Open();

                count = comm.ExecuteNonQuery();
            }
            if (count > 0)
                return true;
            else
                return false;
        }

        public bool GetMessages(out List<Util.GbookMessage> mList)
        {
            mList = new List<Util.GbookMessage>();
            SqlDataReader sdr;

            using (SqlConnection con = new SqlConnection())
            {
                con.ConnectionString = ConfigurationManager.ConnectionStrings["FProj"].ConnectionString;
                con.Open();
                String strSQL = "SELECT * FROM Gbook ORDER BY dbo.Gbook.Date DESC";
                SqlCommand comm = new SqlCommand(strSQL, con);
                sdr = comm.ExecuteReader(CommandBehavior.CloseConnection);

                if (sdr != null)
                {
                    while (sdr.Read())
                    {
                        mList.Add(new Util.GbookMessage { AuthorName = sdr["AuthorName"].ToString(), AuthorEmail = sdr["AuthorEmail"].ToString(), Date = sdr["Date"].ToString(), Text = sdr["Text"].ToString() });
                    }
                }
            }

            return true;
        }
        
    }
}